import request from '@ohos.request';
import prompt from '@ohos.prompt';
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

var globalThis;
var up = 1;
var down = 1
export default {
    data: {
        title: "",
        capturer:null,
        audioRenderer:null,
        display:false,
        isRecord:false,
        path:"",
        fd:0,
        bufSize: 1280,
        url: "", // 视频地址
        autoplay:true,
        controlShow: true, // 是否显示控制栏
        videoId: 'video', // 播放器id
    },
    onInit() {
        let context = featureAbility.getContext()
        let array = ["ohos.permission.MICROPHONE"]
        context.requestPermissionsFromUser(array,1,(err,data)=>{
            console.info("成功获取麦克风权限!")
        })
        //音频采集初始化
        var audioStreamInfo = {
            samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_8000,
            channels: audio.AudioChannel.CHANNEL_1,
            sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_U8,
            encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
        }

        var audioCapturerInfo = {
            source: audio.SourceType.SOURCE_TYPE_MIC,
            capturerFlags: 1
        }

        var audioCapturerOptions = {
            streamInfo: audioStreamInfo,
            capturerInfo: audioCapturerInfo
        }

        audio.createAudioCapturer(audioCapturerOptions,(err, data) => {
            if (err) {
                console.error(`gyf AudioCapturer Created : Error: ${err.message}`);
            }
            else {
                console.info('gyf AudioCapturer Created : Success : SUCCESS');
                this.capturer = data
            }
        });

        //音频播放初始化
        var audioRendererInfo = {
            content: audio.ContentType.CONTENT_TYPE_SPEECH,
            usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
            rendererFlags: 1
        }

        var audioRendererOptions = {
            streamInfo: audioStreamInfo,
            rendererInfo: audioRendererInfo
        }

        audio.createAudioRenderer(audioRendererOptions).then((data) => {
            this.audioRenderer = data;
            console.info('gyf AudioRenderer Created : Success : Stream Type: SUCCESS');
        }).catch((err) => {
            console.info('gyf AudioRenderer Created : ERROR : '+err.message);
        });

        globalThis = this;
    },

    upload(){
        let file1 = { filename: "test", name: "test", uri: this.path, type: "wav" };
        let data = { name: "name123", value: "123" };
        let header = { key1: "value1", key2: "value2" };
        let uploadTask;
        request.upload({
            url: "http://124.70.5.225:8000/api/uploadfile/",
            header: header,
            method: "POST",
            files: [file1],
            data: [data]
        }).then((data) => {
            prompt.showToast({
                message:"上传成功",
                duration:2000
            })
            uploadTask = data;
            uploadTask.on('progress', function callback(uploadedSize, totalSize) {
                console.info("dialogPages=====upload totalSize:" + totalSize + "  uploadedSize:" + uploadedSize);
            });
        }).catch((err) => {
            prompt.showToast({
                message:"上传失败",
                duration:2000
            })
            console.error('dialogPages=====Failed to request the upload. Cause: ' + JSON.stringify(err));
        })
    },

    record() {
        globalThis.isRecord = true;
        var context = featureAbility.getContext();
        let that = this;
        context.getFilesDir().then(function (dir) {
            globalThis.path = dir + "/audio_record.wav";
            that.url = that.path
            console.log("gyf path = " + globalThis.path);
            //打开录音文件
            globalThis.fd = fileio.openSync(globalThis.path, 0o2|0o100|0o1000, 0o666);

            //wav文件写上头部数据 start
            let header = globalThis.encodeWAV();
            console.log("gyf header len = " + header.buffer.byteLength);
            fileio.writeSync(globalThis.fd, header.buffer);
            //wav文件写上头部数据 end

            globalThis.capturer.start().then(function () {
                console.log("gyf start");
                globalThis.capturer.getBufferSize((err, bufferSize) => {
                    if (err) {
                        console.error('gyf getBufferSize error');
                    } else {
                        console.log("gyf bufferSize = " + bufferSize);
                        globalThis.getBuf(bufferSize);
                    }
                });

            });
        });

    },

    recordstop() {
        globalThis.isRecord = false;
        console.log("gyf recordstop");
        globalThis.capturer.stop().then(function (result) {
            console.log("gyf stop result = " + result);
            //            globalThis.capturer.release((err) => {
            //                if (err) {
            //                    console.error('gyf capturer release failed');
            //                } else {
            //                    console.log('gyf capturer released.');
            //                }
            //            });
        });
    },

    play() {
        this.display = true;
    },

    playstop() {
        this.display = false;
    },

    onDestroy() {
        console.log("gyf onDestroy!");
        globalThis.capturer.release((err) => {
            if (err) {
                console.error('gyf capturer release failed');
            } else {
                console.log('gyf capturer released.');
            }
        });

    },

    getData(bufSize) {
        console.log("gyf getData");
        globalThis.capturer.read(bufSize, true).then(this.handleBuffer);
    },

    getBuf(bufSize) {
        console.log("gyf getBuf");
        this.getData(bufSize);
    },

    //循环调用read，进行数据的读取
    handleBuffer(arrayBuffer) {
        console.log("gyf handleBuffer");

        let result = new Uint8Array(arrayBuffer);
        console.log("gyf handleBuffer ================== " + result);

        let outData = this.test(result, up, down);

        fileio.writeSync(globalThis.fd, outData.buffer);

        globalThis.capturer.read(globalThis.bufSize, true).then(this.handleBuffer);

    },

    test(data, up, down) {
        let downData = this.down(data, down);
        let upData = this.up(downData, up);
        return upData;
    },

    writeString(data, offset, str) {
        for (var i = 0; i < str.length; i++) {
            data.setUint8(offset + i, str.charCodeAt(i));
        }
    },

    //变速又变调(+)
    up(data, up) {
        if (1 == up) {
            return data;
        }
        let length = data.byteLength;
        let upLength = Math.round(length / up);
        var upData = new Uint8Array(upLength);
        for (var i = 0, j = 0; i < length; ) {
            if (j >= upLength) {
                break;
            }
            upData[j] = data[i];
            i += up;
            j++;
        }
        return upData;
    },

    //变速又变调(-)
    down(data, down) {
        if (1 == down) {
            return data;
        }

        let length = data.byteLength;
        let downLength = Math.round(length * down);
        var downData = new Uint8Array(downLength);
        for (var i = 0, j = 0; i < length - 1; ) {
            for (var k = 0; k < down; k++) {
                downData[j] = data[i];
                j++;
            }
            i++;
        }
        return downData;
    },

    // 拖动进度条调用
    seeked(e) {
        this.showPrompt('设置进度：' + e.currenttime + '秒');
        console.log("gyf seeked ");
    },

    // 视频准备完成时触发该事件
    prepared(e) {
        this.showPrompt('时长：' + e.duration + '秒');
        console.log("gyf prepared time1 : " + JSON.stringify(e));
    },

    // 音视频开始播放
    start() {
        this.showPrompt('开始播放');
        console.log("gyf start");
    },
    // 音视频暂停播放
    pause() {
        this.showPrompt('暂停播放');
        console.log("gyf pause");
    },
    // 音视频播放完成
    finish() {
        this.$element('confirmDialog').show();
        console.log("gyf finish");
    },

    // 点击视频
    hideControls() {
        this.controlShow = !this.controlShow;
    },

    // dialog确定
    confirm() {
        this.$element('video').start();
        this.$element('confirmDialog').close();
    },

    // dialog取消
    cancel() {
        this.$element('confirmDialog').close();
    },
    // 弹框
    showPrompt(msg) {
        prompt.showToast({
            message: msg,
            duration: 1000
        });
    },
    //假设数据为1000秒钟的时间（8000 * 1000）
    encodeWAV() {
        var dataLen = 8000000;
        var sampleRate = 8000;
        var sampleBits = 8;
        var buffer = new ArrayBuffer(44);
        var data = new DataView(buffer);

        var channelCount = 1;   // 单声道
        var offset = 0;

        // 资源交换文件标识符
        this.writeString(data, offset, 'RIFF'); offset += 4;
        // 下个地址开始到文件尾总字节数,即文件大小-8
        data.setUint32(offset, 36 + dataLen, true); offset += 4;
        // WAV文件标志
        this.writeString(data, offset, 'WAVE'); offset += 4;
        // 波形格式标志
        this.writeString(data, offset, 'fmt '); offset += 4;
        // 过滤字节,一般为 0x10 = 16
        data.setUint32(offset, 16, true); offset += 4;
        // 格式类别 (PCM形式采样数据)
        data.setUint16(offset, 1, true); offset += 2;
        // 通道数
        data.setUint16(offset, channelCount, true); offset += 2;
        // 采样率,每秒样本数,表示每个通道的播放速度
        data.setUint32(offset, sampleRate, true); offset += 4;
        // 波形数据传输率 (每秒平均字节数) 单声道×每秒数据位数×每样本数据位/8
        data.setUint32(offset, channelCount * sampleRate * (sampleBits / 8), true); offset += 4;
        // 快数据调整数 采样一次占用字节数 单声道×每样本的数据位数/8
        data.setUint16(offset, channelCount * (sampleBits / 8), true); offset += 2;
        // 每样本数据位数
        data.setUint16(offset, sampleBits, true); offset += 2;
        // 数据标识符
        this.writeString(data, offset, 'data'); offset += 4;
        // 采样数据总数,即数据总大小-44
        data.setUint32(offset, dataLen, true); offset += 4;

        return data;
    },
}